package model;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.Vector;

import org.apache.xerces.dom.DocumentImpl;
import org.w3c.dom.Document;

import net.sf.vcard4j.java.AddressBook;
import net.sf.vcard4j.java.VCard;
import net.sf.vcard4j.parser.DomParser;

public class AddressBookWrapper {
	
	private AddressBook abook;
	private Vector<VCardWrapper> cards = null;
	
	public static AddressBookWrapper parseAddressBook(String addressBookFilePath) throws Exception {
			
		DomParser parser = new DomParser();
		Document document = new DocumentImpl();
		parser.parse(new FileInputStream(addressBookFilePath), document);
		
		AddressBook addressBook = new AddressBook(document);
		
		AddressBookWrapper abookWrapper = new AddressBookWrapper(addressBook);
		return abookWrapper;		
		
	}
	
	public AddressBookWrapper() {
		abook = null;
		cards = new Vector<VCardWrapper>();
	}
	
	private AddressBookWrapper(AddressBook book) {
		abook = book;
	}
	
	public Vector<VCardWrapper> getAddressCards() {
		if(this.cards != null) return this.cards;
		
		Vector<VCardWrapper> cards = new Vector<VCardWrapper>();
		
		if(abook == null || abook.getVCards().hasNext() == false)
			return cards;
		
		try {
			Iterator cardIter = abook.getVCards();
			while(cardIter.hasNext()) {
				VCard currVCard = (VCard) cardIter.next();
				VCardWrapper cardWrapper = new VCardWrapper(currVCard);
				cards.add(cardWrapper);
			}
			
		} catch (Exception exc) {
			exc.printStackTrace();
		}
		
		return cards;
	}
	
	public String print() {
		StringBuffer out = new StringBuffer();
		
		Vector<VCardWrapper> cards = this.getAddressCards();
		for(int i = 0; i < cards.size(); i++) {
			VCardWrapper myCard = cards.get(i);
			out.append("--- BEGIN " + (i+1) + "/" + cards.size() + "----------------------------");
			out.append("\n");
			out.append("Company:\t" + myCard.getCompanyName());
			out.append("\n");
			out.append("Prename:\t" + myCard.getPreName());
			out.append("\n");
			out.append("Lastname:\t" + myCard.getLastName());
			out.append("\n");
			out.append("Email:\t" + myCard.getEmail());
			out.append("\n");
			out.append("Phone:\t" + myCard.getPhone().print());
			out.append("\n");
			out.append("Fax:\t" + myCard.getFax().print());
			out.append("\n");
			out.append(myCard.getAddress().print());
			out.append("--- END   " + (i+1) + "/" + cards.size() + "----------------------------");
			out.append("\n");
		}
		
		return out.toString();
	}
	
	/**
	 * @param filePath
	 * @throws Exception
	 */
	public void writeToFile(String filePath) throws Exception {
		try { 
			
			File file = new File(filePath);
			BufferedWriter fw = new BufferedWriter(new FileWriter(file));
			
			Vector<VCardWrapper> cards = this.getAddressCards();
			for(int i = 0; i < cards.size(); i++) {
				VCardWrapper myCard = cards.get(i);
				fw.write("BEGIN:VCARD\n");
				fw.write("FN:" + myCard.getCompanyName() + "\n");
				fw.write("N:" + myCard.getLastName() + ";" + myCard.getPreName() + "\n");
				fw.write("EMAIL;INTERNET:" + myCard.getEmail() + "\n");
				
				StringBuffer phoneStr = new StringBuffer("TEL;HOME:");
				if(myCard.existsPhone()) {
					if(myCard.getPhone().existsCountryCode())
						phoneStr.append("+" + myCard.getPhone().getCountryCode());
					if(myCard.getPhone().existsAreaCode())
						phoneStr.append("-" + myCard.getPhone().getAreaCode());
					if(myCard.getPhone().existsNumberCode())
						phoneStr.append("-" + myCard.getPhone().getNumberCode());
				}
				phoneStr.append("\n");
				fw.write(phoneStr.toString());
				
				StringBuffer faxStr = new StringBuffer("TEL;FAX:");
				if(myCard.existsFax()) {
					if(myCard.getFax().existsCountryCode())
						faxStr.append("+" + myCard.getFax().getCountryCode());
					if(myCard.getFax().existsAreaCode())
						faxStr.append("-" + myCard.getFax().getAreaCode());
					if(myCard.getFax().existsNumberCode())
						faxStr.append("-" + myCard.getFax().getNumberCode());
				}
				faxStr.append("\n");
				fw.write(faxStr.toString());
				
				StringBuffer addrStr = new StringBuffer("ADR:;;");
				if(myCard.existsAddress()) {
					if(myCard.getAddress().existsStreetAddress()) addrStr.append(myCard.getAddress().getStreet());
					addrStr.append(";");
					if(myCard.getAddress().existsLocality()) addrStr.append(myCard.getAddress().getLocality());
					addrStr.append(";");
					if(myCard.getAddress().existsRegion()) addrStr.append(myCard.getAddress().getRegion());
					addrStr.append(";");
					if(myCard.getAddress().existsPostalCode()) addrStr.append(myCard.getAddress().getPostalCode());
					addrStr.append(";");
					if(myCard.getAddress().existsCountryName()) addrStr.append(myCard.getAddress().getCountryName());
				}
				addrStr.append("\n");
				fw.write(addrStr.toString());
								
				fw.write("END:VCARD\n\n");
			}
			
			fw.flush();
			fw.close();
			
		} catch (Exception exc) {
			exc.printStackTrace();
		}
		
	}
	
}